package cn.work.control;

import cn.work.bean.servicebean;
import cn.work.service.goodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(name = "ServiceEditServlet", urlPatterns = "/ServiceEditServlet")
public class ServiceEditServlet extends HttpServlet {
    private goodsService gdao = new goodsService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);  // Forward to POST method for simplicity
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String serviceId = request.getParameter("id");  // 获取请求中的服务ID

        System.out.println("服务ID: " + serviceId);  // 输出调试信息，确认是否成功获取到ID

        if (serviceId != null) {
            servicebean ser = new servicebean();
            ser.setId(Integer.parseInt(serviceId));  // 设置服务ID

            // 获取其他表单字段数据
            ser.setName(request.getParameter("name"));
            ser.setName(request.getParameter("classname"));
            ser.setDoctor(request.getParameter("doctor"));
            ser.setTime(request.getParameter("time"));
            ser.setPrice(Double.parseDouble(request.getParameter("price")));
            ser.setIntroduction(request.getParameter("introduction"));
            ser.setStatus(request.getParameter("status"));

            // 处理文件上传（如果有图片）
            if (request.getPart("image") != null) {
                Part imagePart = request.getPart("image");
                String fileName = imagePart.getSubmittedFileName();
                if (fileName != null && !fileName.trim().isEmpty()) {
                    // 处理图片上传的逻辑
                    String path = getServletContext().getRealPath("/pictures") + "/" + fileName;
                    imagePart.write(path);
                    ser.setImage("/pictures/" + fileName);
                }
            }

            // 调用 service 层进行更新操作
            gdao.update(ser);  // 这里调用数据库更新操作
            System.out.println("数据已成功修改到数据库！");
            response.sendRedirect("service_list.jsp");  // 跳转到服务列表页面
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "服务ID缺失");
        }
    }
}
